/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.appleframework.web;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.appleframework.Apple;
import org.appleframework.classloader.ApplicationClassloder;
import org.appleframework.exceptions.UnexpectedException;
import org.appleframework.utils.Java;
import org.appleframework.web.Router.Route;
import org.appleframework.web.results.Result;

/**
 *
 * @author zhujg
 */
public class ActionInvoker {

  public static void invoker(HttpRequest request ,HttpResponse response){
    Route route = Router.route(request.method+request.path);
    Result actionResult = null;
    try {
      Method actionMethod = (Method) getActionMethod(route.action)[1];
      ActionSupper.class.getDeclaredField("request").set(null, request);
      ActionSupper.class.getDeclaredField("response").set(null, response);
      ActionSupper.class.getDeclaredField("params").set(null, request.params);
      actionMethod.invoke(null);
    } catch (InvocationTargetException e) {
      actionResult = (Result) e.getTargetException();
    } catch (Exception e) {
      throw new UnexpectedException(e);
    }
    if(actionResult!=null){
			actionResult.apply(request, response);
		}
  }

  public static Object[] getActionMethod(String fullAction) throws ClassNotFoundException{
    Method actionMethod = null;
    Class controllerClass = null;
    if(!fullAction.startsWith("controllers.")){
      fullAction = "controllers."+fullAction;
    }
    String controller = fullAction.substring(0,fullAction.lastIndexOf("."));
    String action = fullAction.substring(fullAction.lastIndexOf(".")+1);
    ApplicationClassloder application = new ApplicationClassloder(Apple.appPath.getAbsolutePath()+"classes"+File.separator);
    controllerClass = application.loadClass(controller);
    actionMethod = Java.findActionMethod(action, controllerClass);
    return new Object[]{controllerClass,actionMethod};
  }
}
